package dk.twu.analyzer.loader;

import dk.twu.analyzer.model.EODRecord;
import dk.twu.analyzer.model.Exchange;
import dk.twu.analyzer.model.ISymbol;
import dk.twu.analyzer.model.Symbol;
import dk.twu.analyzer.util.AnalyzerConfig;
import dk.twu.analyzer.util.DateTimeCleaner;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

public class EODDataLoader {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("ddMMMyyyy");

    private final AnalyzerConfig config;

    public EODDataLoader(AnalyzerConfig config) {
        this.config = config;
    }

    public Collection<EODRecord> loadEODRecords(ISymbol symbolList, Collection<Exchange> exchanges, LocalDate
            fromDate, LocalDate toDate) {
        Collection<EODRecord> eodRecords = new ArrayList<>();
        exchanges.stream().forEach(ex -> {
            File[] files = MarketDataHelper.getFilesForExchange(config, MarketDataHelper.DataType.EOD, ex, Optional
                    .of(fromDate), Optional.of(toDate));
            Arrays.asList(files).stream().forEach(file -> eodRecords.addAll(loadEODRecordFromFile(symbolList, file,
                    ex)));
        });
        return eodRecords;
    }

    private Collection<EODRecord> loadEODRecordFromFile(ISymbol allSymbols, File file, Exchange exchange) {
        Collection<EODRecord> result = new ArrayList<>();
        try {
            Reader reader = new FileReader(file);
            CSVFormat format = CSVFormat.EXCEL.withHeader().withDelimiter(',');
            CSVParser parser = new CSVParser(reader, format);
            for (CSVRecord record : parser) {
                String symbolText = record.get("Symbol");
                String dateText = record.get("Date").replace(" ", "").replace("-", "");
                dateText = DateTimeCleaner.clean(dateText);
                LocalDate date = LocalDate.parse(dateText, DATE_TIME_FORMATTER);
                String openText = record.get("Open");
                String highText = record.get("High");
                String lowText = record.get("Low");
                String closeText = record.get("Close");
                String volumeText = record.get("Volume");
                Optional<Symbol> symbol = allSymbols.getSymbol(symbolText +
                        "." + exchange.getCode());
                if (symbol.isPresent()) {
                    result.add(new EODRecord(symbol.get(), date, Double.valueOf(openText), Double.valueOf(highText),
                            Double.valueOf(lowText), Double.valueOf(closeText), Long.valueOf(volumeText)));
                }
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
